package tables

import (
	"errors"
	"fmt"
	"peilian-api/app/global/variable"
	"peilian-api/app/model"

	"gorm.io/gorm"
)

// 要点评分详情
type PointTextDetail struct {
	Type  string   `json:"type"`
	Label string   `json:"label"`
	Value []string `json:"value"`
	Score float64  `json:"score"`
}

type RealQues struct {
	gorm.Model
	SessionID            uint
	Session              Session
	QuestionID           uint
	Question             Question
	QuestionType         uint    `gorm:"type:tinyint(3);default:0;comment:0原问题1追问"`
	QuestionText         string  `gorm:"type:longtext;comment:问题文本"`
	CurrentTag           uint    `gorm:"type:tinyint(3);default:0;comment:该问题是第几道问题"`
	BelongToID           *uint   `gorm:"default:0;comment:追问问题的父级问题ID;"`
	MainPointScore       float64 `gorm:"type:decimal(5,2);default:0.00;comment:要点覆盖率"`
	MainPointScoreDetail string  `gorm:"comment:要点评分详细信息"`
	AsrScore             float64 `gorm:"type:decimal(5,2);default:0.00;comment:asr字数评分(含标点)"`
	TopicScore           float64 `gorm:"type:decimal(5,2);default:0.00;comment:题目评测得分(语言表述能力*0.2+围绕主题*0.3+要点覆盖*0.5),新版web报告无要点覆盖"`
	LanguageFluencyScore float64 `gorm:"type:decimal(5,2);default:0.00;comment:语言流畅度(asr*0.5+自信度*0.5)"`
	LanguageScore        float64 `gorm:"type:decimal(5,2);default:0.00;comment:语言表述能力评分(语言流畅度+语调气场)/2"`
	CapabilityScore      float64 `gorm:"type:decimal(5,2);default:0.00;comment:能力评分"`
	ThemeScore           float64 `gorm:"type:decimal(5,2);default:0.00;comment:主题评分"`
	//EvaluateScore        float64    `gorm:"type:decimal(5,2);default:0.00;comment:v1.0测评评分结果"`
	Mood               float64    `gorm:"type:decimal(5,2);default:0.00;comment:语气助词多寡(自信度)"`
	Tone               float64    `gorm:"type:decimal(5,2);default:0.00;comment:语调气场"`
	BelongTo           *RealQues  `gorm:"foreignKey:BelongToID"`
	ExtraQuestions     []RealQues `gorm:"foreignKey:BelongToID"`
	Score              float64    `gorm:"type:decimal(5,2);default:0.00;comment:评分"`
	SpeakTime          uint       `gorm:"default:0; comment:文本时长(s),四舍五入时间"`
	AnswerText         string     `gorm:"comment:回答的asr文本"`
	AnswerAudio        string     `gorm:"type:varchar(255);comment:回答的音频地址"`
	Audio              string     `gorm:"type:varchar(255);comment:音频mp3格式"`
	CharacterInfo      string     `json:"character_info" gorm:"comment:性格打分"`
	ExpressScore       float64    `gorm:"type:decimal(5,2);default:0.00;comment:表达能力(语言流畅度+语调气场+主题评分+要点评分)/4.0"`
	PerformanceScore   float64    `gorm:"type:decimal(5,2);default:0.00;comment:表现力(语言表述能力*0.5+围绕主题0.5)"`
	LogicScore         float64    `gorm:"type:decimal(5,2);default:0.00;comment:逻辑思维评测得分 min(围绕主题,逻辑评测)"`
	VerbalExpressScore float64    `gorm:"type:decimal(5,2);default:0.00;comment:公务员言语表达能力评分"`
	PartLabelsCache    string     `gorm:"comment:每道题提取标签词的结果缓存，用于最终标签词生成"`

	QuestionOrigin string `json:"question_origin" gorm:"type:varchar(512);comment:题目来源"`
	AnsAnalysisTag string `json:"ans_analysis_tag" gorm:"type:varchar(512);comment:解析tag"`
	NextType       string `json:"next_type" gorm:"type:varchar(10);default:default;comment:是否是算法推荐的问题, default-不是, recommend-是"`

	Cr *model.CharacterResp `gorm:"-" json:"-"`

	// v1.0版本测评评分结果
	//ProfessionScore float64 `gorm:"type:decimal(5,2);default:0.00;comment:专业能力得分"`
	//GeneralScore    float64 `gorm:"type:decimal(5,2);default:0.00;comment:通用岗位得分"`

	// 以下属性只用于在程序运行时进行对象缓存
	//EvaluateResp *model.LabelEvaluate `gorm:"-" json:"-"`
}

func (r *RealQues) TableName() string {
	return "real_question"
}

func (r *RealQues) BeforeCreate(tx *gorm.DB) (err error) {
	var cnt int64
	err = tx.Model(r).Where("session_id=? and current_tag=?", r.SessionID, r.CurrentTag).Count(&cnt).Error
	if cnt != 0 {
		err = errors.New(fmt.Sprintf("session_id=%s current_tag=%s的记录已经存在", r.SessionID, r.CurrentTag))
	}
	return
}

// 更加id 更新数据
func UpdateMapById(updates map[string]interface{}, id int) error {
	// map[string]interface{}{"audio": variable.Config.UfsInfo.UfsUrl + fileName}
	d := variable.DB.MySQL.Model(RealQues{}).Where("id = ?", id).Updates(updates)
	if d.Error != nil {
		return d.Error
	}
	return nil
}

// 根据id查询数据
func (r *RealQues) GetRealQuestionById(id int) (RealQues, error) {
	// map[string]interface{}{"audio": variable.Config.UfsInfo.UfsUrl + fileName}
	var rq = RealQues{}
	d := variable.DB.MySQL.Model(RealQues{}).Where("id = ?", id).Find(&rq)
	if d.Error != nil {
		return rq, d.Error
	}
	return rq, nil
}

// 根据session_id查询数据
func (r *RealQues) GetRealQuestionBySessionId(sessionId int) ([]RealQues, error) {
	// map[string]interface{}{"audio": variable.Config.UfsInfo.UfsUrl + fileName}
	var rq = []RealQues{}
	if d := variable.DB.MySQL.Model(&RealQues{}).Where("session_id = ?", sessionId).FindInBatches(&rq, 100, func(tx *gorm.DB, batch int) error {
		if batch == 0 {
			return fmt.Errorf("数据库查询异常")
		}
		for i := 0; i < len(rq); i++ {
			if d := variable.DB.MySQL.Model(&Question{}).Where("id = ?", rq[i].QuestionID).Find(&rq[i].Question); d.Error != nil {
				return d.Error
			}
		}
		return nil
	}); d.Error != nil {
		return rq, fmt.Errorf("数据查询异常")
	}
	return rq, nil
}

// 根据session_id查询数据RealQuestion
func (r *RealQues) GetRealQuesBySessionId(sessionId int) ([]RealQues, error) {
	// map[string]interface{}{"audio": variable.Config.UfsInfo.UfsUrl + fileName}
	var rq = []RealQues{}
	variable.DB.MySQL.Model(&RealQues{}).Where("session_id = ?", sessionId).Find(&rq)
	return rq, nil
}
